﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Statuses;
using BusinessLogic;
using BusinessLogic.Security;
using System.ServiceModel;
using DataTier.Entities;

namespace Otgruzka.Controls.UserAccount
{
    public partial class DepartmentEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BingPromptMessages();
            if (!this.IsPostBack)
                BindData();
        }

        /// <summary>
        /// Отображение подсказок из БД
        /// </summary>
        private void BingPromptMessages()
        {
            try
            {
                string[] messages = new PromptMessagesClient().GetPromptMessages(this.AppRelativeVirtualPath.Substring(this.AppRelativeVirtualPath.LastIndexOf("/") + 1)).ToArray();

                if (messages != null && messages.Count() > 0)
                {
                    this.PromptMessagesRepeater.DataSource = messages;
                    this.PromptMessagesRepeater.DataBind();
                    this.PromptMessagesRepeater.Visible = true;
                }
                else
                {
                    this.PromptMessagesRepeater.Visible = false;
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void BindData()
        {
            this.NewIDJur.DataSource = new DictionariesClient().GetJuridicalPersonList(UserPrincipal.Current.UserId);
            this.NewIDJur.DataBind();

            this.Department.DataSource = new DictionariesClient().GetDepartmentList(UserPrincipal.Current.UserId);
            this.Department.DataBind();
        }

        /// <summary>
        /// Обработка строк при заполнении GridView
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Department_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var jurID = e.Row.FindControl("NewJurID") as DropDownList;
                if (jurID != null)
                {
                    jurID.DataSource = new DictionariesClient().GetJuridicalPersonList(UserPrincipal.Current.UserId);
                    jurID.DataBind();
                }
            }
        }

        /// <summary>
        /// Начала редактирование строки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Department_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            this.Department.EditIndex = e.NewEditIndex;

            //Bind data to the GridView control.
            BindData();
        }

        /// <summary>
        /// Отмена редактирования строки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Department_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //Reset the edit index.
            Department.EditIndex = -1;

            //Bind data to the GridView control.
            BindData();
        }


        protected void Department_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var client = new DictionariesClient();
            int departmentId = (int)e.Keys[0];
            try
            {
                client.DeleteDepartment(UserPrincipal.Current.UserId, departmentId);
                BindData();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                string message = client.GetExceptionDetail(ex);
                this.ErrorMessage.Text = message;
                e.Cancel = true;
                return;
            }
            catch (System.Exception exp)
            {
                //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Ошибка удаления : " + exp.Message + "');", true);

                //string message = string.Format("Ошибка удаления: <br />{0}", ExceptionHelper.GetAllMessage(exp));
                //this.ErrorMessage.Text = message;

                e.Cancel = true;
                return;
            }
            //ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Товар успешно удален.');", true);
        }


        /// <summary>
        /// Обновление строки после редактирования
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Department_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DropDownList drdList;
            drdList = (DropDownList)(Department.Rows[e.RowIndex].Cells[1].FindControl("NewJurID"));

            var client = new DictionariesClient();
            try
            {
                var dept = new DepartmentEntity()
                {
                    Name = e.NewValues["Name"] != null ? e.NewValues["Name"].ToString() : "",
                    OfficeNumber = e.NewValues["OfficeNumber"] != null ? e.NewValues["OfficeNumber"].ToString() : "",
                    JuridicalPersonId = (drdList.SelectedItem != null) ? Convert.ToInt32(drdList.SelectedItem.Value) : (int?)null,
                    DepartmentId = e.Keys["DepartmentId"] != null ? Convert.ToInt32(e.Keys["DepartmentId"]) : 0
                };
                client.SaveDepartment(UserPrincipal.Current.UserId, dept);
                Department.EditIndex = -1;
                BindData();
            }
            catch (System.Exception exp)
            {
                this.ErrorMessage.Text = exp.Message;
                e.Cancel = true;
                return;
            }
        }


        /// <summary>
        /// Кнопка сохранения нового юридического лица
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddNewDept_Click(object sender, EventArgs e)
        {
            string newNameDept = this.NewNameDept.Text;
            string newOfficeNumber = this.NewOfficeNumber.Text;
            int newIDJur = (this.NewIDJur.SelectedItem != null) ? Convert.ToInt32(this.NewIDJur.SelectedItem.Value) : 0;

            if (newNameDept.Length > 0 && newIDJur != 0)
            {
                var client = new DictionariesClient();
                try
                {
                    var dept = new DepartmentEntity()
                    {
                        Name = newNameDept,
                        OfficeNumber = newOfficeNumber,
                        JuridicalPersonId = Convert.ToInt32(newIDJur),
                    };
                    client.SaveDepartment(UserPrincipal.Current.UserId, dept);
                    BindData();
                    this.NewNameDept.Text = "";
                    this.NewOfficeNumber.Text = "";
                }
                catch (System.Exception exp)
                {
                    this.ErrorMessage.Text = exp.Message;
                    //return;
                }
            }
            else
            {
                this.ErrorMessage.Text = "Не все поля заполнены!";
                //return;
            }
        }
    }
}